﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
using FikriKibar.Business.Abstract;
using FikriKibar.Common.Entities;
using FikriKibar.Common.Enums;
using FikriKibar.Common.Exceptions;
using FikriKibar.Common.Helpers;
using FikriKibar.Common.Validation.FluentValidation.User;
using FikriKibar.DataAccess;
using FikriKibar.DataAccess.Abstract;
using FikriKibar.Entities.Abstract;
using FikriKibar.Entities.Composite.UserModels;
using FikriKibar.Entities.Concrete;
using FikriKibar.Globalization;

namespace FikriKibar.Business.Concrete
{
    public class UserManager : IUserService
    {
        #region Global Declarations
        private readonly IUserDal _userDal = new EfUserDal();

        private readonly IUserHistoryDal _userHistoryDal = new EfUserHistoryDal();

        private readonly ISessionHistoryDal _sessionHistoryDal = new EfSessionHistoryDal();

        private readonly ISettingDal _settingDal = new EfSettingDal();

        private readonly IUserGroupDal _userGroupDal = new EfUserGroupDal();

        private readonly IRoleLanguageLineDal _roleLanguageLineDal = new EfRoleLanguageLineDal();


        private readonly IUserGroupUserLineDal _userGroupUserLineDal = new EfUserGroupUserLineDal();

        private readonly IUserGroupUserLineHistoryDal _userGroupUserLineHistoryDal = new EfUserGroupUserLineHistoryDal();

        private readonly ILanguageDal _languageDal = new EfLanguageDal();

        private readonly IEmailService _emailService = new EmailManager();

        #endregion

        #region Methods

        public UpdateModel ForgotPassword()
        {
            return new UpdateModel
            {
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };
        }
        public void ForgotPassword(UpdateModel model)
        {
            var validator = new ForgotPasswordValidator(model);
            model.User = new User
            {
                Email = model.Email
            };
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }

            var affectedUser = _userDal.GetByEmail(model.Email);
            if (affectedUser == null)
            {
                throw new NotFoundException(Resources.NotFound);
            }

            var newPassword = SecurityHelper.CreatePassword(8);
            affectedUser.Password = newPassword.ToSha512();
            affectedUser = _userDal.Update(affectedUser);
            affectedUser.Password = newPassword;
            var emailTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\EmailTemplates\\ForgotPassword." + model.SelectedLanguageCode + ".html");
            _emailService.Send(affectedUser, emailTemplatePath, EmailTypes.ForgotPassword);
        }
        public AddModel SignUp()
        {
            return new AddModel
            {
                User = new User(),
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };
        }
        public void SignUp(AddModel model)
        {
            var validator = new AddValidator(model);
            var user = model.User;
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }

            if (_userDal.GetByUsername(user.Username) != null)
            {
                throw new DuplicateException(Resources.UsernameNotDuplicated);
            }
            if (_userDal.GetByEmail(user.Email) != null)
            {
                throw new DuplicateException(string.Format(Resources.EmailNotDuplicated));
            }
            var selectedLanguage = model.LanguageList.Find(m => m.LanguageCode == model.SelectedLanguageCode);
            user.LanguageId = selectedLanguage.Id;
            var password = user.Password;
            user.Password = user.Password.ToSha512();
            user.CreateDate = DateTime.Now;
            user.CreatedBy = 1;
            user.UpdateDate = DateTime.Now;
            user.UpdatedBy = 1;
            var affectedUser = _userDal.Add(user);
            user.CreatedBy = affectedUser.Id;
            user.UpdatedBy = affectedUser.Id;
            user.DisplayOrder = affectedUser.Id;
            affectedUser = _userDal.Update(user);
            var userGroup = _userGroupDal.Filter(e => e.Id == 1).FirstOrDefault();
            if (userGroup != null)
            {
                var userGroupUserLine = new UserGroupUserLine
                {
                    UserId = affectedUser.Id,
                    CreateDate = DateTime.Now,
                    CreatedBy = affectedUser.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = affectedUser.UpdatedBy,
                    UserGroupId = userGroup.Id
                };
                _userGroupUserLineDal.Add(userGroupUserLine);
            }

            var userFilesName = ConfigurationHelper.GetAppSetting("UserFiles");
            var userDirectoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, userFilesName + "\\" + affectedUser.Email.ToMd5());

            if (!Directory.Exists(userDirectoryPath))
            {
                var publicUserFiles = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, userFilesName + "\\Public");
                Directory.CreateDirectory(userDirectoryPath);
                FileHelper.CopyDirectory(publicUserFiles, userDirectoryPath);
            }

            affectedUser.Password = password;
            var emailTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\EmailTemplates\\SignUp." + model.SelectedLanguageCode + ".html");
            _emailService.Send(affectedUser, emailTemplatePath, EmailTypes.Activation);
        }
        public AddModel Add()
        {
            return new AddModel
            {
                User = new User(),
                LanguageList = _languageDal.Filter(e => e.IsApproved)
            };
        }
        public void Add(AddModel model)
        {
            var validator = new AddValidator(model);
            var user = model.User;
            model.LanguageList = _languageDal.Filter(e => e.IsApproved);
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }

            if (_userDal.GetByUsername(user.Username) != null)
            {
                throw new DuplicateException(Resources.UsernameNotDuplicated);
            }
            if (_userDal.GetByEmail(user.Email) != null)
            {
                throw new DuplicateException(string.Format(Resources.EmailNotDuplicated));
            }

            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

            var selectedLanguage = model.LanguageList.Find(m => m.LanguageCode == model.SelectedLanguageCode);
            user.LanguageId = selectedLanguage.Id;
            var password = user.Password;
            user.Password = user.Password.ToSha512();
            user.CreateDate = DateTime.Now;
            user.CreatedBy = fikriKibarIdentity.UserId;
            user.UpdateDate = DateTime.Now;
            user.UpdatedBy = fikriKibarIdentity.UserId;
            var affectedUser = _userDal.Add(user);
            user.DisplayOrder = affectedUser.Id;
            affectedUser = _userDal.Update(user);

            var userGroup = _userGroupDal.Filter(e => e.Id == 1).FirstOrDefault();
            if (userGroup != null)
            {
                var userGroupUserLine = new UserGroupUserLine
                {
                    UserId = affectedUser.Id,
                    CreateDate = DateTime.Now,
                    CreatedBy = affectedUser.CreatedBy,
                    UpdateDate = DateTime.Now,
                    UpdatedBy = affectedUser.UpdatedBy,
                    UserGroupId = userGroup.Id
                };
                _userGroupUserLineDal.Add(userGroupUserLine);
            }

            var userFilesName = ConfigurationHelper.GetAppSetting("UserFiles");
            var userDirectoryPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, userFilesName + "\\" + affectedUser.Email.ToMd5());

            if (!Directory.Exists(userDirectoryPath))
            {
                var publicUserFiles = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, userFilesName + "\\Public");
                Directory.CreateDirectory(userDirectoryPath);
                FileHelper.CopyDirectory(publicUserFiles, userDirectoryPath);
            }

            affectedUser.Password = password;
            var emailTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\EmailTemplates\\SignUp." + model.SelectedLanguageCode + ".html");
            _emailService.Send(affectedUser, emailTemplatePath, EmailTypes.Activation);
        }
        public UpdateModel Update(int id)
        {
            var user = GetById(id);
            var userGroups = new List<UserGroup>();
            if (user == null) throw new NotFoundException();
            var userGroupUserLines = _userGroupUserLineDal.Filter(e => e.UserId == id);
            if (userGroupUserLines != null)
            {
                userGroups.AddRange(userGroupUserLines.Select(item => item.UserGroup));
            }

            var model = new UpdateModel
            {
                User = user,
                LanguageList = _languageDal.Filter(e => e.IsApproved),
                UserGroups = userGroups,
                SelectedLanguageCode = user.Language.LanguageCode

            };

            return model;
        }
        public void Update(UpdateModel model)
        {

            var modelUser = model.User;
            var user = GetById(modelUser.Id);
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var validator = new UpdateValidator(model);

            modelUser.Password = user.Password;
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }


            if (modelUser.Username != user.Username)
            {
                if (_userDal.GetAll().Any(p => p.Username == modelUser.Username))
                {
                    throw new DuplicateException(Resources.UsernameNotDuplicated);
                }
            }

            if (modelUser.Email != user.Email)
            {
                if (_userDal.GetAll().Any(p => p.Email == modelUser.Email))
                {
                    throw new DuplicateException(Resources.EmailNotDuplicated);
                }
            }

            var userHistory = new UserHistory
            {
                UserId = user.Id,
                Username = user.Username,
                Password = user.Password,
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                LanguageId = user.LanguageId,
                CreateDate = user.CreateDate,
                CreatedBy = user.CreatedBy,
                UpdateDate = user.UpdateDate,
                UpdatedBy = user.UpdatedBy,
                DisplayOrder = user.DisplayOrder,
                IsApproved = user.IsApproved,
                IsDeleted = false
            };

            _userHistoryDal.Add(userHistory);
            user.Username = modelUser.Username;
            user.Email = modelUser.Email;
            user.FirstName = modelUser.FirstName;
            user.LastName = modelUser.LastName;
            var selectedLanguage = model.LanguageList.Find(m => m.LanguageCode == model.SelectedLanguageCode);
            user.LanguageId = selectedLanguage.Id;
            user.UpdateDate = DateTime.Now;
            user.UpdatedBy = fikriKibarIdentity.UserId;
            var affectedUser = _userDal.Update(user);
            fikriKibarIdentity.LanguageCode = selectedLanguage.LanguageCode;
            var fikriKibarPrincipal = new FikriKibarPrincipal(fikriKibarIdentity);
            Thread.CurrentPrincipal = fikriKibarPrincipal;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(fikriKibarIdentity.LanguageCode);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(fikriKibarIdentity.LanguageCode);

            var emailTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\EmailTemplates\\UpdateUserInformation." + fikriKibarIdentity.LanguageCode + ".html");
            _emailService.Send(affectedUser, emailTemplatePath, EmailTypes.Update);
            throw new NotFoundException();

        }
        public UpdateModel UpdateMyPassword()
        {
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            return new UpdateModel
            {
                User = GetById(fikriKibarIdentity.UserId)
            };
        }
        public void UpdateMyPassword(UpdateModel model)
        {
            var validator = new UpdatePasswordValidator(model);
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var user = _userDal.GetById(fikriKibarIdentity.UserId);
            if (model.User.OldPassword.ToSha512() != user.Password)
            {
                throw new NotFoundException(Resources.OldPasswordInvalid);
            }

            var userHistory = new UserHistory
            {
                UserId = user.Id,
                Username = user.Username,
                Password = user.Password,
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                LanguageId = user.LanguageId,
                CreateDate = user.CreateDate,
                CreatedBy = user.CreatedBy,
                UpdateDate = user.UpdateDate,
                UpdatedBy = user.UpdatedBy,
                DisplayOrder = user.DisplayOrder,
                IsApproved = user.IsApproved,
                IsDeleted = false
            };

            _userHistoryDal.Add(userHistory);

            var password = model.User.Password;
            user.Password = password.ToSha512();
            user.UpdateDate = DateTime.Now;
            user.UpdatedBy = user.Id;
            model.User = user;

            var affectedUser = _userDal.Update(user);
            affectedUser.Password = password;
            var emailTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\EmailTemplates\\UpdateMyPassword." + fikriKibarIdentity.LanguageCode + ".html");
            _emailService.Send(affectedUser, emailTemplatePath, EmailTypes.UpdatePassword);


        }
        public DetailModel MyAccount()
        {
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var user = GetById(fikriKibarIdentity.UserId);
            var lastLoginTime = DateTime.Now.ToString("G");
            var sessionHistories = _sessionHistoryDal.Filter(e => e.CreatedBy == user.Id);
            if (sessionHistories.Count <= 0)
                return new DetailModel
                {
                    User = user,
                    RemainingSessionTime = _settingDal.GetValueByKey("SessionTimeOut"),
                    LastLoginTime = lastLoginTime
                };
            var lastSession = sessionHistories.OrderByDescending(e => e.UpdateDate).FirstOrDefault();
            if (lastSession != null)
            {
                lastLoginTime = lastSession.UpdateDate.ToString("G");
            }
            return new DetailModel
            {
                User = user,
                RemainingSessionTime = _settingDal.GetValueByKey("SessionTimeOut"),
                LastLoginTime = lastLoginTime
            };
        }
        public UpdateModel UpdateMyInformation()
        {
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

            var model = new UpdateModel
            {
                User = GetById(fikriKibarIdentity.UserId),
                LanguageList = _languageDal.Filter(e => e.IsApproved),
                SelectedLanguageCode = fikriKibarIdentity.LanguageCode

            };

            return model;
        }
        public void UpdateMyInformation(UpdateModel model)
        {
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
            var validator = new UpdateValidator(model);
            var modelUser = model.User;
            modelUser.Password = fikriKibarIdentity.Password;
            var validationResults = validator.Validate();
            if (!validator.IsValid)
            {
                throw new ValidationException(Resources.InvalidEntityMessage)
                {
                    ValidationResult = validationResults
                };
            }

            var user = GetById(fikriKibarIdentity.UserId);
            if (modelUser.Username != user.Username)
            {
                if (_userDal.GetAll().Any(p => p.Username == modelUser.Username))
                {
                    throw new DuplicateException(Resources.UsernameNotDuplicated);
                }
            }

            if (modelUser.Email != user.Email)
            {
                if (_userDal.GetAll().Any(p => p.Email == modelUser.Email))
                {
                    throw new DuplicateException(Resources.EmailNotDuplicated);
                }
            }

            var userHistory = new UserHistory
            {
                UserId = user.Id,
                Username = user.Username,
                Password = user.Password,
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                LanguageId = user.LanguageId,
                CreateDate = user.CreateDate,
                CreatedBy = user.CreatedBy,
                UpdateDate = user.UpdateDate,
                UpdatedBy = user.UpdatedBy,
                DisplayOrder = user.DisplayOrder,
                IsApproved = user.IsApproved,
                IsDeleted = false
            };

            _userHistoryDal.Add(userHistory);



            user.Username = modelUser.Username;
            user.Email = modelUser.Email;
            user.FirstName = modelUser.FirstName;
            user.LastName = modelUser.LastName;
            var selectedLanguage = model.LanguageList.Find(m => m.LanguageCode == model.SelectedLanguageCode);
            user.LanguageId = selectedLanguage.Id;
            user.UpdateDate = DateTime.Now;
            user.UpdatedBy = fikriKibarIdentity.UserId;
            var affectedUser = _userDal.Update(user);
            fikriKibarIdentity.LanguageCode = selectedLanguage.LanguageCode;
            var fikriKibarPrincipal = new FikriKibarPrincipal(fikriKibarIdentity);
            Thread.CurrentPrincipal = fikriKibarPrincipal;
            Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(fikriKibarIdentity.LanguageCode);
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(fikriKibarIdentity.LanguageCode);

            var emailTemplatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Assets\\EmailTemplates\\UpdateUserInformation." + fikriKibarIdentity.LanguageCode + ".html");
            _emailService.Send(affectedUser, emailTemplatePath, EmailTypes.Update);

        }
        public ListModel GetList(string searchTerm, int selectedRoleId, int status, int index, int size, string idsForSort, string idsForApprove, string idsForDelete)
        {
            var rl =
                _roleLanguageLineDal.Filter(e => e.Language.LanguageCode == Thread.CurrentThread.CurrentCulture.Name);

            var model = new ListModel
            {
                Paging = new Paging(),
                ItemList = new List<User>(),
                RoleList = rl
            };

            if (idsForDelete != null)
            {
                var ids = idsForDelete;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                DeleteSelected(idList);

            }
            model.IdsForDelete = null;

            if (idsForApprove != null)
            {
                var ids = idsForApprove;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                ApproveSelected(idList);
            }

            model.IdsForApprove = null;

            var sortHelper = new SortHelper<User>();
            sortHelper.OrderBy(t => t.DisplayOrder);

            model.Paging.CurrentPageSize = size;
            model.Paging.CurrentPage = index;
            model.SelectedStatus = status;

            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.Paging.TotalItemCount = _userDal.GetTotalCount(e => (e.Username.Contains(searchTerm) || e.FirstName.Contains(searchTerm) || e.LastName.Contains(searchTerm)) && e.IsApproved == blStatus);



            }
            else
            {
                model.Paging.TotalItemCount = _userDal.GetTotalCount(e => (e.Username.Contains(searchTerm) || e.FirstName.Contains(searchTerm) || e.LastName.Contains(searchTerm)));
            }

            var pageSizeListSetting = _settingDal.GetValueByKey("PageSizeList");
            var pageSizeSettingValue = "10,25,50,100";
            if (pageSizeListSetting != null)
            {
                pageSizeSettingValue = pageSizeListSetting;
            }
            var pageSizeList = pageSizeSettingValue.Split(',').Select(t => new KeyValuePair<int, string>(t.ConvertToInt(), t)).ToList();

            pageSizeList.Insert(0, new KeyValuePair<int, string>(-1, "[" + Resources.All + "]"));
            model.Paging.PageSizeList = pageSizeList;


            if (status != -1)
            {
                var blStatus = status.ToString().ConvertToBoolean();
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _userDal.Filter(e => (e.Username.Contains(searchTerm) || e.FirstName.Contains(searchTerm) || e.LastName.Contains(searchTerm)) && e.IsApproved == blStatus, sortHelper, index, size) : _userDal.Filter(e => (e.Username.Contains(searchTerm) || e.FirstName.Contains(searchTerm) || e.LastName.Contains(searchTerm)) && e.IsApproved == blStatus);
            }
            else
            {
                model.ItemList = model.Paging.CurrentPageSize > 0 ? _userDal.Filter(e => (e.Username.Contains(searchTerm) || e.FirstName.Contains(searchTerm) || e.LastName.Contains(searchTerm)), sortHelper, index, size) : _userDal.Filter(e => (e.Username.Contains(searchTerm) || e.FirstName.Contains(searchTerm) || e.LastName.Contains(searchTerm)));
            }


            if (idsForSort != null)
            {
                var ids = idsForSort;
                ids = ids.Remove(ids.Length - 1);
                var idArray = ids.Split(',');
                var idList = idArray.Select(id => id.ConvertToInt()).ToList();
                model.ItemList = SaveSort(idList);
            }
            model.IdsForSort = null;
            model.Searched = searchTerm;
            model.SelectedRoleId = selectedRoleId;
            model.Paging.CurrentPage = index;
            model.Paging.TotalPageCount = (int)Math.Ceiling((float)model.Paging.TotalItemCount / size);
            return model;
        }
        public void Delete(int id)
        {
            var user = _userDal.GetById(id);
            if (user == null) return;
            var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;

            var userGroupUserLines = _userGroupUserLineDal.Filter(e => e.UserId == user.Id);
            foreach (var userGroupUserLine in userGroupUserLines)
            {
                var userRoleLineHistory = new UserGroupUserLineHistory
                {
                    UserGroupUserLineId = userGroupUserLine.Id,
                    UserGroupId = userGroupUserLine.UserGroupId,
                    UserId = userGroupUserLine.UserId,
                    CreateDate = userGroupUserLine.CreateDate,
                    CreatedBy = userGroupUserLine.CreatedBy,
                    UpdateDate = userGroupUserLine.UpdateDate,
                    UpdatedBy = userGroupUserLine.UpdatedBy,
                    IsDeleted = true
                };

                _userGroupUserLineHistoryDal.Add(userRoleLineHistory);
                _userGroupUserLineDal.Delete(userGroupUserLine);
            }
            var userHistory = new UserHistory
            {
                UserId = user.Id,
                Username = user.Username,
                Password = user.Password,
                Email = user.Email,
                FirstName = user.FirstName,
                LastName = user.LastName,
                LanguageId = user.LanguageId,
                CreateDate = user.CreateDate,
                CreatedBy = user.CreatedBy,
                UpdateDate = user.UpdateDate,
                UpdatedBy = user.UpdatedBy,
                DisplayOrder = user.DisplayOrder,
                IsApproved = user.IsApproved,
                IsDeleted = true
            };
            _userHistoryDal.Add(userHistory);
            user.UpdateDate = DateTime.Now;
            user.UpdatedBy = fikriKibarIdentity.UserId;
            user.IsApproved = false;
            _userDal.Update(user);
        }
        private User GetById(int userId)
        {
            return _userDal.GetById(userId);
        }
        private List<User> SaveSort(IReadOnlyList<int> idList)
        {
            var returnedValue = new List<User>();
            for (var i = 0; i < idList.Count; i++)
            {
                var user = _userDal.GetById(idList[i]);
                if (user == null) continue;
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
                var userHistory = new UserHistory
                {
                    UserId = user.Id,
                    Username = user.Username,
                    Password = user.Password,
                    Email = user.Email,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    LanguageId = user.LanguageId,
                    CreateDate = user.CreateDate,
                    CreatedBy = user.CreatedBy,
                    UpdateDate = user.UpdateDate,
                    UpdatedBy = user.UpdatedBy,
                    DisplayOrder = user.DisplayOrder,
                    IsApproved = user.IsApproved,
                    IsDeleted = false
                };
                _userHistoryDal.Add(userHistory);
                user.DisplayOrder = i + 1;
                user.UpdatedBy = fikriKibarIdentity.UserId;
                user.UpdateDate = DateTime.Now;
                _userDal.Update(user);
                returnedValue.Add(user);
            }
            return returnedValue;
        }
        private void DeleteSelected(IEnumerable<int> idList)
        {
            foreach (var id in idList)
            {
                Delete(id);
            }
        }
        private void ApproveSelected(IEnumerable<int> idList)
        {
            foreach (var id in idList)
            {
                var user = _userDal.GetById(id);
                if (user == null) continue;
                var fikriKibarIdentity = (FikriKibarIdentity)Thread.CurrentPrincipal.Identity;
                var userHistory = new UserHistory
                {
                    UserId = user.Id,
                    Username = user.Username,
                    Password = user.Password,
                    Email = user.Email,
                    FirstName = user.FirstName,
                    LastName = user.LastName,
                    LanguageId = user.LanguageId,
                    CreateDate = user.CreateDate,
                    CreatedBy = user.CreatedBy,
                    UpdateDate = user.UpdateDate,
                    UpdatedBy = user.UpdatedBy,
                    DisplayOrder = user.DisplayOrder,
                    IsApproved = user.IsApproved,
                    IsDeleted = false
                };
                _userHistoryDal.Add(userHistory);
                user.UpdatedBy = fikriKibarIdentity.UserId;
                user.UpdateDate = DateTime.Now;
                user.IsApproved = true;
                _userDal.Update(user);
            }
        }

        #endregion
    }
}
